﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CPPEI.Coolzon.UI.PetroleumDataPartLib
{
    /// <summary>
    /// Interaction logic for PartOilTank.xaml
    /// </summary>
    [System.ComponentModel.DisplayName("油罐")]
    [XPartIcon("pack://application:,,,/CPPEI.Coolzon.UI.PetroleumDataPartLib;component/Images/PartIcons/油罐.png")]
    public partial class PartOilTank : DataItemPart
    {
        Storyboard _storyboard;

        #region Property
        public static readonly DependencyProperty ValueProperty =
           DependencyProperty.Register("Value", typeof(double), typeof(PartOilTank),
           new PropertyMetadata(double.NaN, new PropertyChangedCallback(OnValuePropertyChange)));

        public static readonly DependencyProperty CapacityFillBrushProperty =
          DependencyProperty.Register("CapacityFillBrush", typeof(BrushEx), typeof(PartOilTank),
          new PropertyMetadata(OnCapacityFillBrushPropertyChange));

        private double _XMaximum;
        private double _XMinimum;
        private Thickness _XCapacityRangeOffset;
        private ImageSourceFile _XTankBackgroundImage;
        private BrushEx _XCapacityEmptyBrush;
        private string _XTextFormat;
        private double? _XFontSize;
        private TextAlignment _XTextAlign;
        private System.Windows.Media.FontFamily _XFont;

        #endregion

        #region XProperty

        [Category("Data")]
        [DisplayName("最大值")]
        [Description("Maximum")]
        [Editor(typeof(UI.XProperty.Editors.XDoubleEditor), typeof(UI.XProperty.XPropertyValueEditor))]
        [XProperty(XPropertyCategory.Data, "Maximum", "最大值")]
        public double XMaximum
        {
            get
            {
                return _XMaximum;
            }
            set
            {
                _XMaximum = value;
                Refresh();
            }
        }

        [Category("Data")]
        [DisplayName("最小值")]
        [Description("Minimum")]
        [Editor(typeof(UI.XProperty.Editors.XDoubleEditor), typeof(UI.XProperty.XPropertyValueEditor))]
        [XProperty(XPropertyCategory.Data, "Minimum", "最小值")]
        public double XMinimum
        {
            get
            {
                return _XMinimum;
            }
            set
            {
                _XMinimum = value;
                Refresh();
            }
        }

        [Category("Data")]
        [DisplayName("当前值")]
        [Description("Value")]
        [Editor(typeof(UI.XProperty.Editors.XDoubleEditor), typeof(UI.XProperty.XPropertyValueEditor))]
        [XProperty(XPropertyCategory.Data, "Value", "当前值")]
        public double XValue
        {
            get
            {
                return (double)GetValue(ValueProperty);
            }
            set
            {
                SetValue(ValueProperty, value);
            }
        }
        [Category("Data")]
        [DisplayName("罐容区域的限定值")]
        [Description("CapacityRangeOffset")]
        [Editor(typeof(UI.XProperty.Editors.XThicknessEditor), typeof(UI.XProperty.XPropertyValueEditor))]
        [XProperty(XPropertyCategory.Data, "CapacityRangeOffset", "罐容区域的限定值")]
        public Thickness XCapacityRangeOffset
        {
            get
            {
                return _XCapacityRangeOffset;
            }
            set
            {
                _XCapacityRangeOffset = value;
                Refresh();
            }
        }
        [Category("Data")]
        [DisplayName("油罐背景图")]
        [Description("TankBackgroundImage")]
        [Editor(typeof(UI.XProperty.Editors.XImageSourceFileEditor), typeof(UI.XProperty.XPropertyValueEditor))]
        [XProperty(XPropertyCategory.Data, "TankBackgroundImage", "油罐背景图")]
        public ImageSourceFile XTankBackgroundImage
        {
            get
            {
                return _XTankBackgroundImage;
            }
            set
            {
                _XTankBackgroundImage = value;
                Refresh();
            }
        }

        ///// <summary>
        ///// 空罐区域颜色
        ///// </summary>
        //[XProperty(XPropertyCategory.Data, "CapacityEmptyBrush", "空罐区域颜色")]
        //public Brush XCapacityEmptyBrush
        //{
        //    get
        //    {
        //        return _XCapacityEmptyBrush;
        //    }
        //    set
        //    {
        //        _XCapacityEmptyBrush = value;
        //        Refresh();
        //    }
        //}
        [Category("Data")]
        [DisplayName("非空罐区域颜色")]
        [Description("CapacityFillBrush")]
        [Editor(typeof(UI.XProperty.Editors.XBrushEditor), typeof(UI.XProperty.XPropertyValueEditor))]
        [XProperty(XPropertyCategory.Data, "CapacityFillBrush", "非空罐区域颜色")]
        public BrushEx XCapacityFillBrush
        {
            get
            {
                return (BrushEx)GetValue(CapacityFillBrushProperty);
            }
            set
            {
                SetValue(CapacityFillBrushProperty, value);
            }
        }
        [Category("其他")]
        [DisplayName("文本格式化")]
        [Description("TextFormat")]
        [Editor(typeof(UI.XProperty.Editors.XStringEditor), typeof(UI.XProperty.XPropertyValueEditor))]
        [XProperty(XPropertyCategory.Other, "TextFormat", "文本格式化")]
        public string XTextFormat
        {
            get
            {
                return _XTextFormat;
            }
            set
            {
                _XTextFormat = value;
                Refresh();
            }
        }

        [Category("其他")]
        [DisplayName("字体大小")]
        [Description("FontSize")]
        [Editor(typeof(UI.XProperty.Editors.XDoubleEditor), typeof(UI.XProperty.XPropertyValueEditor))]
        [XProperty(XPropertyCategory.Other, "FontSize", "字体大小")]
        public double? XFontSize
        {
            get
            {
                return _XFontSize;
            }
            set
            {
                _XFontSize = value;
                Refresh();
            }
        }

        [Category("其他")]
        [DisplayName("字体位置")]
        [Description("TextAlign")]
        [Editor(typeof(UI.XProperty.Editors.XTextAlignmentEditor), typeof(UI.XProperty.XPropertyValueEditor))]
        [XProperty(XPropertyCategory.Other, "TextAlign", "字体位置")]
        public TextAlignment XTextAlign
        {
            get
            {
                return _XTextAlign;
            }
            set
            {
                _XTextAlign = value;
                Refresh();
            }
        }

        [Category("其他")]
        [DisplayName("字体样式")]
        [Description("Font")]
        [Editor(typeof(UI.XProperty.Editors.XFontFamilyEditor), typeof(UI.XProperty.XPropertyValueEditor))]
        [XProperty(XPropertyCategory.Other, "Font", "字体样式")]
        public FontFamily XFont
        {
            get
            {
                return _XFont;
            }
            set
            {
                _XFont = value;
                Refresh();
            }
        }
        #endregion

        public PartOilTank()
        {
            SetDefaultDataResult();
            InitializeComponent();
        }
        protected override void OnInit(PartContext context)
        {
            base.OnInit(context);
            XMinimum = 0.0f;
            XValue = 0.5f;
            XCapacityRangeOffset = new Thickness(40, 60, 30, 50);
            XCapacityFillBrush = new BrushEx(new SolidColorBrush(Colors.Red), "");
            XFont = new FontFamily("微软雅黑");

            progressRec.Visibility = System.Windows.Visibility.Hidden;
            XMaximum = 100;
            XDataItemId = "data1";
            XDataSeriesId = "series1";
        }
        private void SetDefaultDataResult()
        {
            Random random = new Random();
            ServiceProxy.DataServiceRef.DataSeries[] series = new ServiceProxy.DataServiceRef.DataSeries[1];
            ServiceProxy.DataServiceRef.DataItem[] tmpItems = new ServiceProxy.DataServiceRef.DataItem[1];
            tmpItems[0] = new ServiceProxy.DataServiceRef.DataItem();
            tmpItems[0].Id = "data1";
            tmpItems[0].Name = "data1";
            tmpItems[0].Value = (random.NextDouble() * 120).ToString("F2");

            series[0] = new ServiceProxy.DataServiceRef.DataSeries();
            series[0].Id = "series1";
            series[0].Name = "series1";
            series[0].DataItems = tmpItems;
            DataResult = new ServiceProxy.DataServiceRef.DataResult();
            DataResult.DataSeries = series;
        }
        protected override void OnApplyXProperty()
        {
            base.OnApplyXProperty();
            if(tbText == null)
            {
                return;
            }

            //if (XCapacityEmptyBrush != null)
            //{
            //    bgRec.Fill = XCapacityEmptyBrush;
            //}
            if (XCapacityFillBrush != null)
            {
                //progressRec.Background = XCapacityFillBrush;
                centerRect.Fill = XCapacityFillBrush.Brush;
                topEllip.Fill = XCapacityFillBrush.Brush;
            }
            if (XTankBackgroundImage != null)
            {
                bgImage.Source = XTankBackgroundImage.ImageSource;
            }

            if (XFontSize != null)
            {
                tbText.FontSize = XFontSize.Value;
            }
            tbText.TextAlignment = XTextAlign;
            if (XFont != null)
            {
                tbText.FontFamily = XFont;
            }
            if (XForeground != null)
            {
                tbText.Foreground = XForeground.Brush;
            }
        }
        protected override void OnActive(PartContext context)
        {
            base.OnActive(context);
        }

        protected override void OnDeactive(PartContext context)
        {
            if (_storyboard != null)
            {
                _storyboard.Stop();
                _storyboard.Remove();
                _storyboard = null;
            }

            base.OnDeactive(context);
        }

        protected override void OnDestory()
        {
            if (_storyboard != null)
            {
                _storyboard.Stop();
                _storyboard.Remove();
                _storyboard = null;
            }
            base.OnDestory();
        }

        /// <summary>
        /// 更新显示
        /// </summary>
        public void RefreshDraw()
        {
            if (this.DataItem != null)
            {
                progressRec.Visibility = System.Windows.Visibility.Visible;
                this.tbText.Text = this.FormartText(this.DataItem.Id, this.DataItem.Name, XValue.ToString("F2"));

                if (this.ActualWidth > 0 && this.ActualHeight > 0 && bgImage.Source != null)
                {
                    double originalHeight = bgImage.Source.Height;
                    double originalWidth = bgImage.Source.Width;
                    double curOffsetTop = (this.ActualHeight / originalHeight) * this.XCapacityRangeOffset.Top;
                    double curOffsetBottom = (this.ActualHeight / originalHeight) * this.XCapacityRangeOffset.Bottom;
                    double curOffsetLeft = (this.ActualWidth / originalWidth) * this.XCapacityRangeOffset.Left;
                    double curOffsetRight = (this.ActualWidth / originalWidth) * this.XCapacityRangeOffset.Right;

                    this.bgRec.Margin = new Thickness(curOffsetLeft, curOffsetTop, curOffsetRight, curOffsetBottom);
                    progressRec.Margin = new Thickness(curOffsetLeft, curOffsetTop, curOffsetRight, curOffsetBottom);

                    double scale = (XValue - XMinimum) / (XMaximum - XMinimum);

                    if (scale > 1.0d)
                    {
                        scale = 1.0d;
                    }

                    if((bgRec.ActualHeight - topEllip.ActualHeight) > 0)
                    {
                        _ctlBody.Height = (bgRec.ActualHeight - topEllip.ActualHeight) * scale;
                    }

                }
            }
        }

        protected override void OnDataItemBinding(CPPEI.Coolzon.ServiceProxy.DataServiceRef.DataItem dataItem)
        {
            if (_storyboard != null)
            {
                _storyboard.Stop();
                _storyboard.Remove();
                _storyboard = null;
            }

            _storyboard = new Storyboard();

            DoubleAnimation doubleAnimation = new DoubleAnimation(XMinimum, Convert.ToDouble(dataItem.Value), new Duration(TimeSpan.FromSeconds(XDataAnimationDuration)));
            //this.BeginAnimation(ValueProperty, doubleAnimation);
            Storyboard.SetTarget(doubleAnimation, this);
            Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath(PartOilTank.ValueProperty));
            _storyboard.Children.Add(doubleAnimation);
            _storyboard.Begin();
        }

        private static void OnValuePropertyChange(DependencyObject send, DependencyPropertyChangedEventArgs e)
        {
            PartOilTank pot = send as PartOilTank;
            if ((double)e.NewValue < pot.XMinimum) return;
            pot.RefreshDraw();
        }

        private static void OnCapacityFillBrushPropertyChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PartOilTank pot = d as PartOilTank;

            if (e.NewValue != null && pot.centerRect != null)
            {
                pot.centerRect.Fill = (e.NewValue as BrushEx).Brush;
                pot.topEllip.Fill = (e.NewValue as BrushEx).Brush;
                pot.bottomEllip.Fill = (e.NewValue as BrushEx).Brush;
            }
        }

        [Obsolete("存在bug，文本格式的处理需要处理")]
        private string FormartText(string dataItemId, string dataItemName, string dataValue)
        {
            if (!string.IsNullOrEmpty(XTextFormat))
            {
                if (XTextFormat == "{data.Value:0.00}")
                {
                    return XTextFormat.Replace("{data.Value:0.00}", string.Format("{0:N2}", Common.Convertor.ToDouble(dataValue)));
                }
                else if (XTextFormat == "{data.Value:0.0}")
                {
                    return XTextFormat.Replace("{data.Value:0.0}", string.Format("{0:N1}", Common.Convertor.ToDouble(dataValue)));
                }
                else
                {
                    return XTextFormat.Replace("{data.Value}", string.Format("{0:N0}", Common.Convertor.ToDouble(dataValue)));
                }
            }
            return dataValue;
        }
    }
}
